/**
 * name: common
 * version: v3.0.0
 * update: 去掉pc端跨屏支持
 * date: 2016-04-30
 */
define(function(require, exports, module) {
    var $ = require('jquery');
    var base = require('base');
    require('box');
    //未检测到jquery时引入bootstrap
    /*var needjq = !window.$;
    if(needjq){
        base.getScript(['lib/bootstrap3/bootstrap.min',seajs.root + '/public/default/js/common'],{
            jquery:true,
            css: seajs.root + '/public/default/css/common.css'
        });
    }*/

    if(base.browser.ie<9){
        alert('您的浏览器版本过低，请升级或使用chrome、Firefox等高级浏览器！');
    }
    //屏蔽ie78 console未定义错误
    if (typeof console === 'undefined') {
        console = { log: function() {}, warn: function() {} }
    };
    /*
    * 常用工具
    */
    $message = $('._message');
    if( parseInt($message.attr('data-num')) > 0 ){
        $message.addClass('hasfeed cur');
    }

    //返回顶部
    $('body').on('click','.gotop',function(){$('html,body').stop(1).animate({scrollTop:'0'},300);return false});
    //关闭当前页
    $('body').on('click','.closewin',function(){window.opener=null;window.open("","_self");window.close()});
    //打印当前页
    $('body').on('click','.print',function(){window.print()});
    
    //textarea扩展max-length
    $('textarea[max-length]').on('change blur keyup',function(){
        var _val=$(this).val(),_max=$(this).attr('max-length');
        if(_val.length>_max){
            $(this).val(_val.substr(0,_max));
        };
    });
    //延时显示
    if(base.browser.ie<9){
        $('.opc0').css('filter','unset')
    }else{
        $('.opc0').animate({'opacity':'1'},160);
    }
    // placeholder
    if(base.browser.ie<10){
        var $inputs = $('input,textarea');
        $inputs.placeholder()//.focus();
        /*setTimeout(function(){
            $inputs.blur()
        },10000)*/
    }

    //按需渲染
    base.scanpush();
    //响应图片
    base.resImg();


    var alertError = function(str,url){
        $.box.msg(str, {
            color: 'danger',
            delay: 2000,
            hook:'alert_tip'
        });
        if( url != undefined && url != 'undefined' ){
            setTimeout(function(){
                window.location.href = url;
            },1500);
        }
    };
    var alertWarning = function(str,url){
        $.box.msg(str, {
            color: 'warning',
            delay: 2000,
            hook:'alert_tip'
        });
        if( url != undefined && url != 'undefined' ){
            setTimeout(function(){
                window.location.href = url;
            },1500);
        }
    };
    var alertSuccess = function(str,url){
        $.box.msg(str, {
            delay: 2000,
            hook:'alert_tip'
        });
        if( url != undefined && url != 'undefined' ){
            setTimeout(function(){
                window.location.href = url;
            },1500);
        }
    };
    var returnResult = function(multiple,string){
        if( multiple ){
            return {status:false,str:string};
        }else{
            $.box.alert(string);
            return false;
        }
    };
    var confirmMsg = function(str,oktext,canceltext,okfunction,cancelfunction,color){
        $.box.sooc(str, okfunction,cancelfunction,{
            oktext: oktext,
            canceltext:canceltext,
            color:color
        });
    };
    //上传配置检测
    checkUploadFile = function(file,extension,file_size){
        var multiple = true;
        file.name = file.name.replace(/\'/g,"").toLowerCase();
        if(file.name.length>=40){
            return returnResult(multiple,'您上传的文件名称超过40个字符不能上传');
        }
        if(file.name.length > 1 && file.name ) {
            var ldot = file.name.lastIndexOf(".");
            var file_type = file.name.substring(ldot + 1);
        }
        if(extension.indexOf(file_type) < 0){
            return returnResult(multiple,'您上传的文件类型不允许，不能上传！');
        }
        if(file_size === '' || file_size === undefined || file_size === 'undefined'){
            if((file_type == 'jpg' || file_type == 'png' || file_type == 'jpeg' || file_type == 'ico') && file.size > (10*1024*1024) ){
                return returnResult(multiple,'图片大小超过10M不能上传');
            }
            if((file_type == 'doc' || file_type == 'docx' || file_type == 'ppt' || file_type == 'pptx') && file.size > (10*1024*1024) ){
                return returnResult(multiple,'文档大小超过10M不能上传');
            }
        }else{
            if( extension.indexOf(file_type)>=0 && file.size>(file_size*1024*1024) ){
                return returnResult(multiple,'文件大小超过'+file_size+'M不能上传');
            }
        }
        if(multiple){
            return {status:true,str:'检测文件成功'};
        }
        return true;
    };

    //pluploader+qiniujs 通用上传
    require('../lib/qiniu/plupload.js');
    getFileExt = function (str){
        var strar = str.split('.');
        return strar[strar.length-1];
    };
    setFileKey = function(filename){
        var date = new Date();
        var month = "0"+parseInt(date.getMonth()+1);
        month = month.substr(-2);
        var day = "0"+date.getDate();
        day = day.substr(-2);
        var newtime = date.getFullYear()+''+month+''+day;
        var guid = "";
        for (var i = 1; i <= 8; i++){
            var n = Math.floor(Math.random()*16.0).toString(16);
            guid +=   n;
            if((i==4)||(i==12)||(i==16)||(i==20))
                guid += "-";
        }
        var ext = getFileExt(filename);
        return newtime+'_'+date.getTime()+guid+'.'+ext;
    };
    var newAddUpload = function (pickerDom,mmt,multiple,up_success,file_size) {
        var extension;
        if(mmt == 'img'){
            extension = "jpg,png,jpeg,ico";
        }else if(mmt == 'video'){
            extension = "avi,rm,rmvb,wmv,flv,mpg,mpeg,mp4,mov,3gp,mkv";
        }else if(mmt == 'doc'){
            extension = "doc,docx,ppt,pptx";
        }else if(mmt == 'all'){
            extension = "jpg,png,jpeg,ico,doc,docx,ppt,pptx,avi,rm,rmvb,wmv,flv,mpg,mpeg,mp4,mov,3gp,mkv";
        }else if(mmt == 'no_video'){
            extension = "jpg,png,jpeg,ico,doc,docx,ppt,pptx,zip,rar"
        }else if(mmt == 'fujian'){
            extension = "jpg,png,jpeg,ico,doc,docx,ppt,pptx,avi,rm,rmvb,wmv,flv,mpg,mpeg,mp4,mov,3gp,mkv,zip,rar"
        }

        var state_box = $('#'+pickerDom).parent().find('.upload_state');
        var uploader = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickerDom,
            filters : {
                max_file_size : '1000mb',
                prevent_duplicates: true,   //不允许选取重复文件
                mime_types:[
                            {title : "files", extensions:extension}
                        ]
            },
            flash_swf_url: '/static/lib/qiniu/Moxie.swf',
            dragdrop: true,
            chunk_size: '4mb',
            multi_selection: multiple,
            uptoken_func: function(file){
                if(file.name.length > 1 && file.name ) {       
                    var ldot = file.name.lastIndexOf(".");
                    var file_type = file.name.substring(ldot + 1);
                };
                var upToken;
                $.ajax({
                    type: "GET",
                    url: '/index.php/api/V1/File/getQiniuToken',
                    data:{ext:file_type},
                    dataType: 'json',
                    async: false,
                    success:function(res){
                        upToken = res.uptoken;
                    }
                });
                return upToken;
            },
            domain:'/',
            get_new_uptoken:true,
            auto_start:true,
            log_level:0,
            init: {
                'FilesAdded': function(up, files) {
                    plupload.each(files, function(file) {
                        var result  = checkUploadFile(file,extension,file_size);
                        var msg = '';
                        if( !result.status ){
                            msg = result.str;
                        };
                        var $li = $(
                            '<a id="'+file.id+'" class="file-item" style="cursor: pointer;">' +
                            '<div class="upinfo"><span class="title">' + file.name + '</span> <span class="red">'+msg+'</span><span class="r remove_upload" onclick="remove_queue('+file.id+');$(this).parent().parent().remove();"><i class="ion">&#xe637;</i> </span></div><div style="clear:both;"></div><div class="upprogress"><span></span></div>' +
                            '</a>'
                        );
                        if(msg != ''){
                            alertError(msg);
                            uploader.removeFile(file.id);
                        };
                        state_box.append( $li );
                    });
                    //移除队列
                    remove_queue = function(id){
                        uploader.removeFile(id);
                    };
                },
                'BeforeUpload': function(up, file) {
                    //上传前
                },
                'UploadProgress': function(up, file) {
                    var $li = $( '#'+file.id ),
                        $percent = $li.find('.upprogress span');
                    $percent.css( 'width', file.percent + '%' );
                },
                'UploadComplete': function(up) {
                    state_box.empty();
                },
                'FileUploaded': function(up, file, response) {
                    alertSuccess('上传成功');
                    $('#'+file.id).remove();
                    eval("response = " + response);
                    var hash = response.hash,
                        key = response.key,
                        persistentId = response.persistentId || '',
                        size = file.size;
                    if(file.name.length > 1 && file.name ) {
                        var ldot = file.name.lastIndexOf(".");
                        var file_type = file.name.substring(ldot + 1);
                    }
                    $.ajax({
                        type: "POST",
                        url: '/index.php/api/V1/File/add',
                        data:{hash:hash,key:key,persistentId:persistentId,size:size,type:file_type,name:file.name},
                        dataType: 'json',
                        async: false,
                        success:function(res){
                            up_success(file,res);
                        }
                    });
                },
                'Error': function(up, err, errTip) {
                    console.log(errTip);
                    alertError('上传失败');
                },
                'Key': function(up,file) {
                    return setFileKey(file.name);
                }
            }
        });
    };

    /*
    * 输出
    */
    module.exports = {
        // //sooc:function(message, sureCall, cancelCall, options){
        confirmSuccess:function(str,oktext,canceltext,okfunction,cancelfunction){
            confirmMsg(str,oktext,canceltext,okfunction,cancelfunction,'success');
        },
        confirmError:function(str,oktext,canceltext,okfunction,cancelfunction){
            confirmMsg(str,oktext,canceltext,okfunction,cancelfunction,'error');
        },
        confirmWarning:function(str,oktext,canceltext,okfunction,cancelfunction){
            confirmMsg(str,oktext,canceltext,okfunction,cancelfunction,'warning');
        },
        get_file_ext:function(file_name){
            //var str = new Array();
            var str = file_name.split(".");
            var ext = str[str.length - 1];
            return ext.toLowerCase();
        },
        alertError : alertError,
        alertSuccess : alertSuccess,
        alertWarning : alertWarning,
        newAddUpload : newAddUpload,
        checkUploadFile : checkUploadFile
    }
    /*
    * 站内公用
    */
    
    // require('tab');
    // $('.channel_tab').tab({
    //     posi_auto:false,
    //     callback:function(a,b,c){
    //         a.find('.sch_tab_hd').find('.st').eq(0).trigger('click');
    //     }
    // });
    
    $.fn.tab=function(){
        var $key=$(this).find('.st'),
            $val=$(this).find('.sc');
        $key.first().addClass('active');
        $val.first().show().siblings().hide();
        $key.each(function(index){
            $(this).click(function(event){
                event.preventDefault();
                $(this).addClass('active').siblings().removeClass('active');
                $val.hide().eq(index).show();
            })
        })
    };
    $('.sch_tab').each(function(){$(this).tab()});


    $('.l_menus').find('.tab_t').children('a').click(function(e){
        var s_url = $(this).data('url');
        if(s_url){
            e.preventDefault();
            $('.channel_right').children('.tab_c').html('加载中...');
            $(this).parent('.tab_t').addClass('tab_t_cur').siblings().removeClass('tab_t_cur');
            $.ajax({
                url:s_url,
                dataType:'html',
                success:function(html) {
                    $('.channel_right').children('.tab_c').html(html);
                }
            })
        }
    });
    $('.l_menus').find('.tab_t_cur').children('a').trigger('click');

    //设置导航
    var navid = $('#showNav').val();
    if(navid){
        $('.pageNav').children('ul').children('li').removeClass('cur');
        $('.pageNav').find('#'+navid).addClass('cur');
    }


})
